package org.unique.web.interceptor;

import java.util.List;

import org.unique.common.tools.CollectionUtil;
import org.unique.web.annotation.Intercept;

/**
 * 拦截器工厂接口
 * @author：rex
 * @create_time：2014-6-25 下午3:06:36  
 * @version：V1.0
 */
public class InterceptorFactory {

	private static final List<Interceptor> interceptorListTemp = CollectionUtil.newArrayList();
	private static final List<Interceptor> interceptorList = CollectionUtil.newArrayList();

	public static void setInterceptor(Interceptor interceptor){
		interceptorListTemp.add(interceptor);
	}
	
	public static void setInterceptor(Class<?> interceptor){
		Object obj = null;
		try {
			obj = interceptor.newInstance();
			if(null != obj && obj instanceof Interceptor){
				interceptorListTemp.add((Interceptor)obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化拦截器
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void buildInterceptor() throws InstantiationException, IllegalAccessException {
//		String interPack = Const.CONST_MAP.get("unique.globalInterceptor");
//		if (StringUtils.isNotBlank(interPack)) {
//			String pack = interPack.trim();
//			List<Interceptor> interceptorListTemp = CollectionUtil.newArrayList();
//			Set<Class<?>> classes = ClassHelper.scanPackage(pack);
//			for (Class<?> clazz : classes) {
//				if (Interceptor.class.isAssignableFrom(clazz) && null != clazz.getAnnotation(Intercept.class)) {
//					interceptorListTemp.add((Interceptor) clazz.newInstance());
//				}
//			}
//			interceptorList.addAll(interceptorListTemp);
//			for (Interceptor interceptor : interceptorListTemp) {
//				if (null != interceptor.getClass().getAnnotation(Intercept.class)) {
//					int v = interceptor.getClass().getAnnotation(Intercept.class).loadOnStartup();
//					interceptorList.set(v, interceptor);
//				}
//			}
//		}
		interceptorList.addAll(interceptorListTemp);
		for (Interceptor interceptor : interceptorListTemp) {
			int v = interceptor.getClass().getAnnotation(Intercept.class).loadOnStartup();
			interceptorList.set(v, interceptor);
		}
	}

	public static List<Interceptor> getInterceptors() {
		return interceptorList;
	}
}
